package com.alwvfhp.tools.Powershell.thread;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.alwvfhp.tools.Powershell.ResultCode;
import com.alwvfhp.tools.Powershell.interf.PResult;

public class PowerShellThread<T extends PResult> implements Runnable {
	/**
	 * 保存运行的结果
	 */
	private T result;
	/**
	 * "
	 * 保存运行的文件
	 */
	private String fileName;
	
	public PowerShellThread(T result,String fileName){
		this.result=result;
		this.fileName=fileName;
	}
	public void run() {
		Runtime r = Runtime.getRuntime();
		Process pr = null;
		try {
			String order="cmd /c powershell "+fileName+".ps1";
			pr = r.exec(order);
			BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK"));
			String line=null;
			while((line=br.readLine())!=null){
				line=line.trim();
				if("".equals(line))continue;
				if("OK".equals(line))break;
				this.result.add(line);
			}
			br.close();
			/*****按照评估把错误信息读出来(考虑到错误信息不是太多，就一次性读出来)*****/
			InputStream is = pr.getErrorStream();
			int esize = is.available();
			if(esize>0){//如果评估有，那么证明这次运行出错
				byte[] error=new byte[esize+5];
				is.read(error, 0, esize);
				String errormsg=new String(error,"GBK");
				for(String err:errormsg.split("\n")){
					this.result.adderror(err);
				}
				is.close();
				this.result.setRCode(ResultCode.FAIL);
			}
			/*****按照评估把错误信息读出来(考虑到错误信息不是太多，就一次性读出来)*****/
			else this.result.setRCode(ResultCode.OK);//运行成功
			new File(fileName+".ps1").delete();//删除文件
		} catch (Exception e) {//运行失败
			this.result.setRCode(ResultCode.FAIL);
			this.result.adderror(e.toString());
		}
		finally{
			if(null!=pr)pr.destroy();
		}
	}
}
